package cn.com.anypay.manager.service.impl;

import cn.com.anypay.manager.common.utils.AnyJsonUtils;
import cn.com.anypay.manager.dto.config.payment.WxAppConfig;
import cn.com.anypay.manager.service.UserAuthService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 微信用户授权服务实现类
 */
@Slf4j
@Service
public class WxpayUserAuthServiceImpl implements UserAuthService {
    private static final String AUTH_SCOPE = "snsapi_base";
    private final RestTemplate restTemplate = new RestTemplate();
    @Autowired
    @Qualifier("wxPayMpConfig")
    private WxAppConfig mpConfig;

    @Override
    public String buildAuthUrl(String appId, String redirectUri) {
        try {
            log.info("=== 生成微信授权链接开始 ===");
            log.info("回调地址: {}", redirectUri);

            // 1. 对回调地址进行编码
            String encodedRedirectUri = URLEncoder.encode(redirectUri, StandardCharsets.UTF_8.toString());

            // 2. 生成授权链接
            String authUrl = String.format(
                "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=STATE#wechat_redirect",
                appId,
                encodedRedirectUri,
                AUTH_SCOPE
            );

            log.info("生成的授权链接: {}", authUrl);
            return authUrl;
        } catch (Exception e) {
            log.error("生成微信授权链接失败: {}", e.getMessage(), e);
            throw new RuntimeException("生成微信授权链接失败", e);
        }
    }

    @Override
    public Map<String, Object> exchangeAuthCodeForToken(String appId, String authCode, String privateKey) {
        try {
            log.info("=== 获取微信用户OpenID开始 ===");
            log.info("授权码: {}", authCode);

            // 1. 构建请求URL
            String url = String.format(
                "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                appId,
                mpConfig.getSecret(),
                authCode
            );

            // 2. 发送请求获取access_token和openid
            String response = restTemplate.getForObject(url, String.class);
            Map<String, Object> result = AnyJsonUtils.toMap(response);

            // 3. 检查返回结果
            if (result.containsKey("errcode")) {
                log.error("获取OpenID失败: {}", result.get("errmsg"));
                throw new RuntimeException("获取OpenID失败：" + result.get("errmsg"));
            }

            String openId = (String) result.get("openid");
            String accessToken = (String) result.get("access_token");
            String refreshToken = (String) result.get("refresh_token");
            Integer expiresIn = (Integer) result.get("expires_in");
            String scope = (String) result.get("scope");

            log.info("获取OpenID成功: openId={}, accessToken={}, expiresIn={}",
                openId, accessToken, expiresIn);

            // 4. 返回成功结果
            Map<String, Object> tokenInfo = new HashMap<>();
            tokenInfo.put("openid", openId);
            tokenInfo.put("access_token", accessToken);
            tokenInfo.put("refresh_token", refreshToken);
            tokenInfo.put("expires_in", expiresIn);
            tokenInfo.put("scope", scope);

            return tokenInfo;
        } catch (Exception e) {
            log.error("获取微信用户OpenID失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取微信用户OpenID失败: " + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getUserProfile(String appId, String accessToken, String privateKey) {
        try {
            log.info("=== 获取微信用户信息开始 ===");
            log.info("accessToken: {}", accessToken);

            // 1. 构建请求URL
            String url = String.format(
                "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN",
                accessToken,
                appId  // 这里appId实际上是openid
            );

            // 2. 发送请求获取用户信息
            String response = restTemplate.getForObject(url, String.class);
            Map<String, Object> result = AnyJsonUtils.toMap(response);

            // 3. 检查返回结果
            if (result.containsKey("errcode")) {
                log.error("获取用户信息失败: {}", result.get("errmsg"));
                throw new RuntimeException("获取用户信息失败：" + result.get("errmsg"));
            }

            log.info("获取用户信息成功: {}", result);
            return result;
        } catch (Exception e) {
            log.error("获取微信用户信息失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取微信用户信息失败: " + e.getMessage());
        }
    }
}